<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-7-24
 * Time: 下午3:25
 */

namespace home\models;


use common\components\tools\Security;
use common\models\db\User;
use yii\base\Model;

/**
 * Class FormSignup
 * @package home\models
 */
class FormSignup extends Model
{
    public $username;
    public $email;
    public $password;
    public $repassword;
    public $code;

    public function attributeLabels()
    {
        return [
            'username' => "用户名",
            'email' => "邮箱",
            'password' => "密码",
            'repassword' => "重复密码",
            'code' => "验证码",
        ];
    }

    public function rules()
    {
        return [
            [['username', 'email'], 'trim'],
            [['username', 'email', 'password', 'code'], 'required'],
            [['username'], 'string', 'max' => 20],
            ['username', 'unique', 'targetClass' => User::class, 'targetAttribute' => 'username'],
            [['email'], 'string', 'max' => 200],
            ['email', 'unique', 'targetClass' => User::class, 'targetAttribute' => 'email'],
            ['email', 'email'],
            ['password', 'string', 'min' => 6, 'max' => 20],
            ['repassword', 'compare', 'compareAttribute' => 'password'],
            ['code', 'string', 'min' => 4, 'max' => 4],
            ['code', 'captcha'],
        ];
    }

    public function signup()
    {
        if (!$this->validate()){
            return null;
        }
        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->token = \Yii::$app->security->generateRandomString(50);
        $user->setPassword($this->password);
        $user->auth_key = \Yii::$app->security->generateRandomString();
        $user->created_at = Yii_BT_TIME;
        $user->updated_at = Yii_BT_TIME;
        $user->random_string = \Yii::$app->security->generateRandomString();
        $code = $user->generateCode();
        $link = \Yii::$app->urlManager->createAbsoluteUrl(['site/active-email', 'email'=>$this->email, 'code'=>$code]);
        $html = \Yii::$app->controller->renderPartial('/emails/signup', ['link' => $link]);
        \Yii::$app->mailer->compose()->setTo($this->email)->setSubject("账号激活链接")->setHtmlBody($html)->send();
        $user->status = $user::STATUS_EMAIL_UNACTIVE;
        return $user->save() ? $user : null;
    }
}